package com.ruoyi.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.ParkingBlack;
import com.ruoyi.domain.ParkingInfo;
import com.ruoyi.mapper.ParkingInfoMapper;
import com.ruoyi.service.IParkingInfoService;
import com.ruoyi.wss.WebSocketMessageService;
import com.ruoyi.wss.dahua.Enum.MasWebsocketEnum;
import com.ruoyi.wss.dahua.config.DaHuaConfig;
import com.ruoyi.wss.dahua.request.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mapper.ParkingWhiteMapper;
import com.ruoyi.domain.ParkingWhite;
import com.ruoyi.service.IParkingWhiteService;

import javax.annotation.Resource;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;


/**
 * 白名单
Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-04
 */
@Service
@Slf4j
public class ParkingWhiteServiceImpl implements IParkingWhiteService 
{
    @Resource
    private ParkingWhiteMapper parkingWhiteMapper;
    @Resource
    private ParkingInfoMapper parkingInfoMapper;
    @Autowired
    private WebSocketMessageService webSocketMessageService;

    /**
     * 查询白名单
     * 
     * @param whiteId 白名单主键
     * @return 白名单

     */
    @Override
    public ParkingWhite selectParkingWhiteByWhiteId(Long whiteId)
    {
        return parkingWhiteMapper.selectParkingWhiteByWhiteId(whiteId);
    }

    /**
     * 查询白名单列表
     * 
     * @param parkingWhite 白名单
     * @return 白名单

     */
    @Override
    public List<ParkingWhite> selectParkingWhiteList(ParkingWhite parkingWhite)
    {
        return parkingWhiteMapper.selectParkingWhiteList(parkingWhite);
    }

    /**
     * 新增白名单
     * 
     * @param parkingWhite 白名单
     * @return 结果
     */
    @Override
    public int insertParkingWhite(ParkingWhite parkingWhite)
    {
        ParkingWhite query = new ParkingWhite();
        query.setCarNum(parkingWhite.getCarNum());
        List<ParkingWhite> list = parkingWhiteMapper.selectParkingWhiteList(query);
        if (list.size() > 0){
            throw new RuntimeException("车牌已存在");
        }
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingWhite.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }

        Boolean result = sendRequest(DaHuaConfig.BLACK_ADD, parkingWhite, parkingInfo);
        if(result){
            parkingWhite.setIssuanceStatus("1");
        }else {
            parkingWhite.setIssuanceStatus("0");
        }
        parkingWhite.setCreateBy(getUsername());
        parkingWhite.setCreateTime(DateUtils.getNowDate());
        parkingWhite.setDeptId(parkingInfo.getDeptId());
        parkingWhite.setDelFlag("0");
        parkingWhiteMapper.insertParkingWhite(parkingWhite);
        return 1;
    }

    /**
     * 修改白名单
     * 
     * @param parkingWhite 白名单
     * @return 结果
     */
    @Override
    public int updateParkingWhite(ParkingWhite parkingWhite)
    {
        ParkingWhite query = new ParkingWhite();
        query.setCarNum(parkingWhite.getCarNum());
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingWhite.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }
        Boolean result = sendRequest(DaHuaConfig.BLACK_UPDATE, parkingWhite, parkingInfo);
        if(result){
            parkingWhite.setIssuanceStatus("1");
        }else {
            parkingWhite.setIssuanceStatus("0");
        }
        parkingWhite.setUpdateBy(getUsername());
        parkingWhite.setUpdateTime(DateUtils.getNowDate());
        parkingWhite.setDeptId(parkingInfo.getDeptId());
        parkingWhite.setDelFlag("0");
        parkingWhiteMapper.updateParkingWhite(parkingWhite);
        return 1;
    }

    /**
     * 批量删除白名单
     * 
     * @param whiteIds 需要删除的白名单主键
     * @return 结果
     */
    @Override
    public int deleteParkingWhiteByWhiteIds(Long[] whiteIds)
    {
        return parkingWhiteMapper.deleteParkingWhiteByWhiteIds(whiteIds);
    }

    /**
     * 删除白名单信息
     * 
     * @param whiteId 白名单主键
     * @return 结果
     */
    @Override
    public int deleteParkingWhiteByWhiteId(Long whiteId)
    {
        ParkingWhite parkingWhite = parkingWhiteMapper.selectParkingWhiteByWhiteId(whiteId);
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingWhite.getParkId());
        Date date = DateUtils.getYesterdayDate();
        parkingWhite.setValidStartTime(date);
        parkingWhite.setValidEndTime(date);
        Boolean res = sendRequest(DaHuaConfig.BLACK_DELETE, parkingWhite, parkingInfo);
        if(res){
            parkingWhiteMapper.deleteParkingWhiteByWhiteId(whiteId);
        }else {
            throw new RuntimeException("下发删除指令失败，删除失败");
        }
        return 1;
    }

    @Override
    public int sendRequest(ParkingWhite parkingWhite) {
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingWhite.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }
        Boolean result = sendRequest(DaHuaConfig.BLACK_ADD, parkingWhite, parkingInfo);
        if(result){
            parkingWhite.setIssuanceStatus("1");
            return parkingWhiteMapper.updateParkingWhite(parkingWhite);
        }else {
            throw new RuntimeException("重新下发指令失败！");
        }

    }

    /**
     * 车辆白名单请求
     * @param operateType
     * @param parkingWhite
     * @param parkingInfo
     * @return
     */
    public Boolean sendRequest(Integer operateType, ParkingWhite parkingWhite, ParkingInfo parkingInfo){
        log.info("车辆白名单请求JSON：{}", parkingWhite);
        String platformId = parkingInfo.getPlatformId();
        ParkingWhiteRequest parkingWhiteRequest = null;
        // 组装请求参数
        parkingWhiteRequest = ParkingWhiteRequest.builder()
            .carNum(parkingWhite.getCarNum())
            .parkingLotCodes(parkingInfo.getParkCode())
            .validStartDay(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,parkingWhite.getValidStartTime()))
            .validEndDay(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,parkingWhite.getValidEndTime()))
            .operateTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,DateUtils.getNowDate()))
            .carOwner(parkingWhite.getOwner())
            .phone(parkingWhite.getOwnerTel())
            .build();

        List<ParkingWhiteRequest> list = new ArrayList<>();
        list.add(parkingWhiteRequest);

        ParkingWhiteListRequest parkingWhiteListRequest = new ParkingWhiteListRequest();
        parkingWhiteListRequest.setPlatformId(platformId);
        parkingWhiteListRequest.setCarNum(parkingWhite.getCarNum());
        parkingWhiteListRequest.setWhiteList(list);

        // 发送请求
        RequestData<ParkingWhiteListRequest> requestData = new RequestData<>(
                MasWebsocketEnum.WHITE_CAR_SYNC.getMethod(), parkingWhiteListRequest);
        CommonRequest<ParkingWhiteListRequest> commonRequest = new CommonRequest<>("transform", 1, requestData);
        log.info("车辆白名单请求JSON：{}", parkingWhiteListRequest);
        try {
            Boolean result = webSocketMessageService.operationDevice(platformId, commonRequest);
            if(!result){
                return false;
            }else{
                log.info("车辆白名单成功：{}，下级平台：{}", parkingWhite, platformId);
                return true;
            }
        } catch (Exception ex) {
            log.error("车辆白名单失败：{}，下级平台：{}", ex.getMessage(), platformId);
            return false;
        }
    }
}
